/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utilities;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

/**
 * @author h08125
 */
public class HashFunctions {
    /**
     * @param input: the String you want to convert to MD5
     * @return the md5 hashed string
     * Code from http://viralpatel.net/blogs/java-md5-hashing-salting-password/
     */
    public static String stringToMD5(String input) {
        String md5 = null;
         
        if(input == null) {
            return null;
        }
         
        try {
        //Create MessageDigest object for MD5
        MessageDigest digest = MessageDigest.getInstance("MD5");
         
        //Update input string in message digest
        try {
            digest.update(input.getBytes("UTF-8"), 0, input.length());
        }
        catch (UnsupportedEncodingException e) {
        }
        //Converts message digest value in base 16 (hex) 
        md5 = new BigInteger(1, digest.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
        }
        return md5;
    }
    
    /**
     * Convert a String via sha-1
     * @param password
     * @return 
     * Code from http://stackoverflow.com/a/9071224/968861
     */
    public static String stringToSHA1(String input){
        String sha1 = "";
        try{
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(input.getBytes("UTF-8"));
            sha1 = byteToHex(crypt.digest());
        }
        catch(NoSuchAlgorithmException e){
            e.printStackTrace();
        }
        catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }
        return sha1;
    }
    
    private static String byteToHex(final byte[] hash){
        Formatter formatter = new Formatter();
        for (byte b : hash){
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
}
